package com.cari.oa.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.util.DateUtils;
import com.cari.oa.util.Utils;

@Controller
@SessionAttributes("username")
public abstract  class BaseDownloadController {

    @Resource
	private AttachmentService attachmentService;
    private static final Logger logger = LoggerFactory.getLogger(BaseDownloadController.class);
    
	/**
	* Title: upload
	* Description:上传文件
	* @author     hjx 
	* @date       2013-3-12 
	* @param username
	* @param request
	*/
	public void upload(String username, MultipartHttpServletRequest multipartRequest) {
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		StringBuffer path = new StringBuffer(multipartRequest.getSession().getServletContext().getRealPath("/") + "uploads/");
		File uploadDir = new File(path.toString());
		if (!uploadDir.exists()) uploadDir.mkdir();
		
		Calendar cal = Calendar.getInstance(); 
		String pathTemp = cal.get(Calendar.YEAR) + "_" + cal.get(Calendar.MONTH);
		path.append(pathTemp);
		File monthDir = new File(path.toString());
		if (!monthDir.exists()) monthDir.mkdir();
		
		String fileName = null;
		for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			MultipartFile mf = entry.getValue();
			fileName = mf.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String storeName = DateUtils.date2Str(new Date(), DateUtils.NOT_FORMAT) + "_"+ new Random().nextInt(1000) + "." + fileExt;
			File uploadFile = new File(path.toString()+"/" + storeName);
			try {
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				
				AttachmentEntity att = new AttachmentEntity();
				att.setName(fileName.replaceAll(" ", ""));
				att.setPath("uploads/" + pathTemp + "/" + storeName);
				att.setSuffix(fileExt);
				att.setUploadUser(username);
				att.setObjectType(Integer.valueOf(multipartRequest.getAttribute("ObjectType").toString()));
				att.setObjectId(multipartRequest.getAttribute("ObjectId").toString());
				attachmentService.insert(att);
			} catch (IOException e) {
				logger.error("上传失败", e);
			}
		}
	}
		
	/**
	* Title: download
	* Description:下载
	* @author     hjx 
	* @date       2013-3-12 
	* @param fileName
	* @param path
	* @param request
	* @param response
	 */
	public void download(String fileName, String path,HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			request.setCharacterEncoding("UTF-8");
			long fileLength = new File(request.getSession().getServletContext().getRealPath("/")+path).length();
			response.setContentType("application/x-msdownload;"); 
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1"));  //转码之后下载的文件不会出现中文乱码
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(request.getSession().getServletContext().getRealPath("/")+path));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Title: postDelete
	* Description:
	* @author    hjx 
	* @date       2013-3-13 
	* @param username
	* @param request
	* @param id
	* @param storeName
	* @return
	*/
    public String postDelete(@ModelAttribute("username") String username,HttpServletRequest request, String id,String path) {
    	AttachmentEntity att=attachmentService.getById(id);
        if(att == null) 
        	return Utils.errorJsonResp("文件不存在，请刷新页面");
        path = request.getSession().getServletContext().getRealPath("/")+path ;
        File file=new File(path);
		if(file.exists() && file.delete()){         //检查是否存在,删除文件
			attachmentService.deleteById(id);
		}
        SysOperLogController.addOperLog(username, "ATTACHMENT", "删除文件" + att.getName());
        return Utils.normalJsonResp();
    }
}
